package com.party.jackclientandroid.ui_home.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.party.jackclientandroid.BaseActivityTitle;
import com.party.jackclientandroid.MainActivity;
import com.party.jackclientandroid.R;
import com.party.jackclientandroid.api.DefaultConsumer;
import com.party.jackclientandroid.api.SearchService;
import com.party.jackclientandroid.bean.BaseResult;
import com.party.jackclientandroid.bean.SearchPoint;
import com.party.jackclientandroid.bean.SearchResult;
import com.party.jackclientandroid.event.NeighbourSearchEvent;
import com.party.jackclientandroid.event.ShopSearchEvent;
import com.party.jackclientandroid.ui_mine.choose_location.ChooseLocationActivity;
import com.party.jackclientandroid.utils.ConstUtils;
import com.party.jackclientandroid.utils.DensityUtils;
import com.party.jackclientandroid.utils.SPUtils;
import com.party.jackclientandroid.view.AutoNextLineLinearLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class SearchActivity extends BaseActivityTitle {
    @BindView(R.id.hot_ll)
    AutoNextLineLinearLayout hotLl;
    @BindView(R.id.history_ll)
    AutoNextLineLinearLayout historyLl;
    @BindView(R.id.search_content_delete_iv)
    ImageView search_content_delete_iv;
    @BindView(R.id.history_content_delete_iv)
    ImageView history_content_delete_iv;
    @BindView(R.id.search_content_rv)
    RecyclerView search_content_rv;
    @BindView(R.id.search_et)
    EditText search_et;
    @BindView(R.id.search_list_ll)
    LinearLayout searchListLl;
    @BindView(R.id.no_hot_search_key_tv)
    TextView noHotSearchKeyTv;

    private SearchService searchService = null;
    private List<SearchPoint> searchPointList = new ArrayList<>();
    private CommonAdapter<SearchPoint> commonAdapter;
    private String[] strings;
    private String from;
    int dp_10;
    int dp_5;
    private int chooseShopTypeId = 1;
    private String historySearchKey;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        receivePassDataIfNeed(getIntent());
        initData();
        initListener();
    }

    protected void receivePassDataIfNeed(Intent intent) {
        chooseShopTypeId = intent.getIntExtra("shopTypeId", 1);
        from = intent.getStringExtra("from");
    }

    protected void initData() {
        setMiddleText("搜索");
        historySearchKey = (String) SPUtils.get(mApplication, "history_search_key", "");
        dp_10 = DensityUtils.dip2px(mActivity, 10);
        dp_5 = DensityUtils.dip2px(mActivity, 5);
        searchService = new SearchService(this);
        commonAdapter = new CommonAdapter<SearchPoint>(mActivity, R.layout.item_search_point, searchPointList) {
            @Override
            protected void convert(ViewHolder viewHolder, SearchPoint searchPoint, final int position) {
                viewHolder.setText(R.id.name_tv, searchPoint.getItem());
            }
        };
        search_content_rv.setLayoutManager(new LinearLayoutManager(mActivity));
        search_content_rv.setAdapter(commonAdapter);
        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {

            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        initHistorySearch();
    }

    protected void initListener() {
        search_et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s.toString())) {
                    search_content_delete_iv.setVisibility(View.INVISIBLE);
                    searchListLl.setVisibility(View.GONE);
                } else {
                    search_content_delete_iv.setVisibility(View.VISIBLE);
//                    getSearchPointList(s.toString());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        search_et.setOnEditorActionListener((TextView v, int actionId, KeyEvent event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                startSearch();
                return true;
            }
            return false;
        });
    }


    @OnClick({R.id.search_tv, R.id.search_content_delete_iv, R.id.history_content_delete_iv})
    public void handleClickSth(View v) {
        switch (v.getId()) {
            case R.id.search_tv:
                startSearch();
                break;
            case R.id.search_content_delete_iv:
                search_et.setText("");
                break;
            case R.id.history_content_delete_iv:
                historySearchKey = null;
                SPUtils.remove(mApplication, "history_search_key");
                historyLl.removeAllViews();
                break;
        }
    }

    public void startSearch() {
        if (TextUtils.isEmpty(search_et.getText().toString().trim())) {
            showToast("搜索内容不能为空！");
            return;
        }
        // 主页的搜索点击进来的
        if (!TextUtils.isEmpty(from) && from.equals("homeFragment")) {
            Intent intent = new Intent(mActivity, NearbyActivity.class);
            intent.putExtra("categoryId", "");
            intent.putExtra("conditionType", "1");
            startActivity(intent);
        } else {
            returnActivity(search_et.getText().toString().trim());
        }
        boolean isContain = false;
        if (!TextUtils.isEmpty(historySearchKey)) {
            for (int i = 0; i < strings.length; i++) {
                if (strings[i].equals(search_et.getText().toString())) {
                    isContain = true;
                    break;
                }
            }
        }
        if (!isContain) {
            if (TextUtils.isEmpty(historySearchKey)) {
                historySearchKey = search_et.getText().toString();
            } else {
                historySearchKey = historySearchKey + "," + search_et.getText().toString();
            }
            SPUtils.put(mApplication, "history_search_key", historySearchKey);
            TextView tv = new TextView(this);
            tv.setText(search_et.getText().toString());
            tv.setPadding(dp_10, dp_5, dp_10, dp_5);
            tv.setBackground(getResources().getDrawable(R.drawable.btn_background_hollow_selector));
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            tv.setLayoutParams(layoutParams);
            historyLl.addView(tv);
        }
        finish();
    }

    public void returnActivity(String key) {
        Intent intent = new Intent(SearchActivity.this, MainActivity.class);
        intent.putExtra(ConstUtils.SEARCH_KEY + "", key);
        setResult(RESULT_OK, intent);
    }

    /**
     * 搜索框提示
     *
     * @param name
     */
    public void getSearchPointList(String name) {
        addDisposableIoMain(searchService.getSearchPointList(name), new DefaultConsumer<List<SearchPoint>>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<List<SearchPoint>> baseBean) {
                searchPointList.clear();
                searchPointList.addAll(baseBean.getData());
                searchListLl.setVisibility(View.VISIBLE);
                commonAdapter.notifyDataSetChanged();
            }
        });
    }

    public void initHistorySearch() {
        if (!TextUtils.isEmpty(historySearchKey)) {
            strings = historySearchKey.split(",");
            for (int i = 0; i < strings.length; i++) {
                TextView tv = new TextView(this);
                tv.setText(strings[i]);
                tv.setPadding(dp_10, dp_5, dp_10, dp_5);
                tv.setBackground(getResources().getDrawable(R.drawable.btn_background_hollow_selector));
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                tv.setLayoutParams(layoutParams);
                historyLl.addView(tv);
                tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String str = ((TextView) v).getText().toString();
                        search_et.setText(str);
                        // 主页的搜索点击进来的
                        if (!TextUtils.isEmpty(from) && from.equals("homeFragment")) {
                            Intent intent = new Intent(mActivity, NearbyActivity.class);
                            intent.putExtra("categoryId", "");
                            intent.putExtra("conditionType", "1");
                            intent.putExtra("needSearchKey", search_et.getText().toString().trim());
                            startActivity(intent);
                        } else {
                            returnActivity(search_et.getText().toString().trim());
                        }
                        finish();
                    }
                });
            }
        }
    }
}
